#include <iostream>
using namespace std;

/*
    【题目246】编写一个程序，用友元函数重载运算符的方法，使对实型的运算符+、-、*、/适用于复数运算。
*/

class Complex
{
public:
    Complex(int r, int i) : real(r), imag(i) {}
    friend Complex operator+(const Complex &c1, const Complex &c2)
    {
        return Complex(c1.real + c2.real, c1.imag + c2.imag);
    }

    friend Complex operator-(const Complex &c1, const Complex &c2)
    {
        return Complex(c1.real - c2.real, c1.imag - c2.imag);
    }

    friend Complex operator*(const Complex &c1, const Complex &c2)
    {
        return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
    }

    friend Complex operator/(const Complex &c1, const Complex &c2)
    {
        return Complex((c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag),
                       (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag));
    }

    friend ostream &operator<<(ostream &out, const Complex &c)
    {
        if (c.imag < 0)
        {
            out << c.real << c.imag << "i";
        }
        else
        {
            out << c.real << "+" << c.imag << "i";
        }
        return out;
    }

private:
    int real;
    int imag;
};

int main()
{
    Complex c1(1, 2), c2(3, 4);
    Complex c3 = c1 + c2;
    cout << c3 << endl;

    Complex c4 = c1 - c2;
    cout << c4 << endl;

    Complex c5 = c1 * c2;
    cout << c5 << endl;

    Complex c6 = c1 / c2;
    cout << c6 << endl;
    return 0;
}